package com.heatup.apt.management.service.course.impl;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.heatup.apt.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.common.constants.CourseConstants;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.common.constants.ServiceConstans;
import com.heatup.apt.common.dao.CourseCoachMapper;
import com.heatup.apt.common.dao.CourseInfoMapper;
import com.heatup.apt.common.dao.CourseScheduleMapper;
import com.heatup.apt.common.dao.CourseStandardMapper;
import com.heatup.apt.common.dao.CourseStoreMapper;
import com.heatup.apt.common.dao.OrderInfoMapper;
import com.heatup.apt.common.dao.OrderInfoResultMapper;
import com.heatup.apt.common.dao.ResourceMapper;
import com.heatup.apt.common.dao.ServicePriceMapper;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.management.service.TemplateSendService;
import com.heatup.apt.management.service.course.CourseService;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.ResourceExample;
import com.heatup.apt.model.api.OrderInfoResultModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.course.CoachFeeDetailVo;
import com.heatup.apt.model.course.CourseCoach;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.course.CourseInfoModel;
import com.heatup.apt.model.course.CourseSchedule;
import com.heatup.apt.model.course.CourseStandard;
import com.heatup.apt.model.course.CourseStore;
import com.heatup.apt.model.course.CourseTeamInfo;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.store.StoreInfo;

/**
 * Created by b3st9u on 16/8/22.
 */
@Service
public class CourseServiceImpl implements CourseService {

    protected static final Logger log = LoggerFactory.getLogger(CourseServiceImpl.class);
    @Autowired
    private CourseInfoMapper courseInfoMapper;

    @Autowired
    private CoachInfoMapper coachInfoMapper;

    @Autowired
    private CourseCoachMapper courseCoachMapper;

    @Autowired
    private ServicePriceMapper servicePriceMapper;

    @Autowired
    private CourseScheduleMapper courseScheduleMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private CourseStoreMapper courseStoreMapper;

    @Autowired
    private StoreInfoMapper storeInfoMapper;
    
    @Autowired
    private CourseStandardMapper courseStandardMapper;

    @Autowired
    private OrderInfoResultMapper orderInfoResultMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private TemplateSendService templateSendService;
    
   

    /**
     * 删除檬营课程
     * @param id
     * @return
     */
    @Override
    public boolean delCourseInfoById(int id) {
        if (id <=0)
            return false;
        //清理关联表数据....
        courseCoachMapper.deleteByCourseId(id);
        servicePriceMapper.deleteByCourseId(id);
        courseStoreMapper.deleteByCourseId(id);
        courseScheduleMapper.deleteByCourseId(id);
        resourceMapper.deleteByCourseId(id);
        return courseInfoMapper.deleteById(id) > 0;
    }


    /**
     * 檬营分页查询
     * @param paramsMap
     * @return
     */
    @Override
    public Map<String, Object> queryCourseList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap();
        paramsMap.put("pageNo",(Integer)paramsMap.get("pageIndex") * (Integer)paramsMap.get("pageSize"));
        resultMap.put("courseList", courseInfoMapper.queryCourseList(paramsMap));
        resultMap.put("courseCount", courseInfoMapper.queryCourseCount(paramsMap));

        return resultMap;

    }
    
    /**
     * 团课列表查询
     */
    @Override
    public Map<String, Object> queryCourseTeamList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap();
		List<CoachInfo> coachInfoList = coachInfoMapper.selectList(null);
		List<StoreInfo> storeInfoList = storeInfoMapper.selectList(null);
		paramsMap.put("count", "count");
		int pageIndex = (Integer) paramsMap.get("pageIndex");
		if (pageIndex == 0 || pageIndex == 1) {
			pageIndex = 0;
		} else {
			pageIndex = (pageIndex - 1) * 10;
		}
		paramsMap.put("pageNo", pageIndex);
		paramsMap.put("pageSize", 10);
		List<CourseTeamInfo> courseTeamInfoList = courseInfoMapper.queryCourseTeamList(paramsMap);
		paramsMap.remove("count");
		List<CourseTeamInfo> courseTeamInfoCount = courseInfoMapper.queryCourseTeamList(paramsMap);
		resultMap.put("courseList", courseTeamInfoList);
		resultMap.put("coachList", coachInfoList);
		resultMap.put("storeList", storeInfoList);
		resultMap.put("pageCount", courseTeamInfoCount.size());
		resultMap.put("pageNow", paramsMap.get("pageIndex"));

		resultMap.putAll(paramsMap);
		return resultMap;
    }



    /**
     * 檬营保存
     * @param courseInfoModel
     * @return
     */
    @Override
    @Transactional
    public boolean saveCourse(CourseInfoModel courseInfoModel) {

        int result = 0;
        if (courseInfoModel == null) {
            return false;
        }

        CourseInfo courseInfo = saveCourseInfo(courseInfoModel);

        int courseId = saveCourseCoachStore(courseInfoModel, courseInfo);

        result = saveCourseSchedule(courseInfoModel, courseId);

        saveCourseResource(courseInfoModel, courseId);

        return result >0;
    }
    /**
     * 保存课程教练/门店
     * @param courseInfoModel
     * @param courseInfo
     * @return
     */
    private int saveCourseCoachStore(CourseInfoModel courseInfoModel, CourseInfo courseInfo) {

        int cId = courseInfo.getId();

        CourseCoach courseCoach = new CourseCoach();
        courseCoach.setCourseId(cId);
        courseCoach.setIsMain("1");
        courseCoach.setCoachId(courseInfoModel.getCoachId());

        courseCoachMapper.insertSelective(courseCoach);

        String storeId = courseInfoModel.getStoreId();
        if (StringUtils.isNotBlank(storeId)) {
            String[] stores = storeId.split(",");
            CourseStore courseStore;
            for (String store : stores) {
                courseStore = new CourseStore();
                courseStore.setCourseId(cId);
                courseStore.setStoreId(Integer.valueOf(store));
                courseStoreMapper.insertSelective(courseStore);
            }
        }
        return cId;
    }

    /**
     * 保存课程详情
     * @param courseInfoModel
     * @return
     */
    private CourseInfo saveCourseInfo(CourseInfoModel courseInfoModel) {
        CourseInfo courseInfo = new CourseInfo();
        BeanUtils.copyProperties(courseInfoModel, courseInfo);
        courseInfo.setHeadImg(null);

        courseInfo.setCourseAttr(courseInfoModel.getCourseAttr().replaceAll(",","#"));//多选下拉框默认会将多个值转成[,]数组
        courseInfo.setCourseType(CourseConstants.CourseType.fun_camp.getType());
        courseInfo.setStatus(CourseConstants.CourseStatus.online.getStatus());
        courseInfo.setCourseStandardId(courseInfoModel.getCourseStandardId());
        courseInfo.setCoachCount(1);


        ServicePrice servicePrice = new ServicePrice();
        servicePrice.setServiceName(courseInfo.getTitle());
        servicePrice.setServiceType(ServiceConstans.ServiceType.campCourse.getIndex());
        servicePrice.setPrimePrice(courseInfoModel.getServicePrice().getPrimePrice());
        servicePrice.setPrice(courseInfoModel.getServicePrice().getPrice());
        if (courseInfoModel.getStoreId()!=null) {
            servicePrice.setStoreId(Integer.valueOf(courseInfoModel.getStoreId()));
        }
        Integer serviceId = servicePriceMapper.queryServicePriceByCourseId(courseInfoModel.getId());
        if (courseInfoModel.getId() != null) {

            CourseInfo courseInfoOld = courseInfoMapper.selectById(courseInfoModel.getId());
            //如果 课程最大人数有变化  则触发排队的订单是否要变成正常订单
            if (courseInfoOld != null) {
                if (courseInfo.getMaxCount().compareTo(courseInfoOld.getMaxCount()) > 0) {
                    int waitCout = courseInfoOld.getWaitCount() == null ? 0 : courseInfoOld.getWaitCount();
                    int currentCount = courseInfoOld.getCurrentCount() == null ? 0 : courseInfoOld.getCurrentCount();

                    //查询所有排队的订单
                    List<OrderInfoResultModel> waitOrders = orderInfoResultMapper.selectWaitOrderByServiceId(serviceId);
                    int personCount = 0;
                    for (OrderInfoResultModel waitOrder : waitOrders) {
                        //当前订单人数
                        int curOrderPersonCount = waitOrder.getOrderDetail().getPersonCount() == null ? 0 : waitOrder.getOrderDetail().getPersonCount();
                        personCount += curOrderPersonCount;
                        //当前课程人数应该增加
                        currentCount += curOrderPersonCount;
                        //排队人数减少
                        waitCout -= curOrderPersonCount;
                        //将排队等待的订单更新成预订成功状态
                        waitOrder.setOrderStatus(OrderContants.OrderStatus.NORMAL.getStatus());
                        waitOrder.setUpdatedBy(-1);
                        waitOrder.setUpdatedTime(new Date());
                        orderInfoMapper.updateSelectiveById(waitOrder);
                        templateSendService.sendBookingSuccTemplateMsg(waitOrder.getId(), waitOrder.getOrderStatus());
                        if (personCount >= (courseInfoModel.getMaxCount() - courseInfoOld.getMaxCount())) {
                            break;
                        }
                    }
                    courseInfo.setCurrentCount(currentCount);
                    courseInfo.setWaitCount(waitCout);
                }
            }

            courseInfoModel.setId(courseInfoModel.getId());
            courseInfo.setUpdatedTime(new Date());
            courseInfoMapper.updateSelectiveById(courseInfo);

            servicePrice.setId(serviceId);
            servicePriceMapper.updateByPrimaryKeySelective(servicePrice);
            //清理关联表数据....

            courseCoachMapper.deleteByCourseId(courseInfoModel.getId());
            courseStoreMapper.deleteByCourseId(courseInfoModel.getId());
            courseScheduleMapper.deleteByCourseId(courseInfoModel.getId());
            resourceMapper.deleteByCourseId(courseInfoModel.getId());

        } else {
            courseInfo.setWaitCount(0);

            courseInfo.setCreatedTime(new Date());
            courseInfoMapper.insertSelective(courseInfo);
            servicePrice.setCourseId(courseInfo.getId());
            servicePriceMapper.insertSelective(servicePrice);
        }
        return courseInfo;
    }

    /**
     * 保存课程计划
     * @param courseInfoModel
     * @param courseId
     * @return
     */
    private int saveCourseSchedule(CourseInfoModel courseInfoModel, int courseId) {
        int result;CourseSchedule courseSchedule = new CourseSchedule();
        courseSchedule.setCourseId(courseId);
        courseSchedule.setWeeks(courseInfoModel.getWeeks());

        courseSchedule.setPeriods(courseInfoModel.getPeriods());
        String[] dateStrings = courseInfoModel.getCampClassTime().split(",");
        courseSchedule.setStartTime(DateUtil.parseUtilDate(dateStrings[0],DateUtil.FMT_DATE_YYYYMMDDHHMM));
        courseSchedule.setEndTime(DateUtil.addMinites(DateUtil.parseUtilDate(dateStrings[dateStrings.length-1],DateUtil.FMT_DATE_YYYYMMDDHHMM),90));

//        courseSchedule.setStartTime(courseInfoModel.getStartTime());
//        courseSchedule.setEndTime(courseInfoModel.getEndTime());

        courseSchedule.setWeekly("0");//檬营新课初始关闭签到
        result = courseScheduleMapper.insertSelective(courseSchedule);
        return result;
    }

    /**
     * 保存课程资源
     * @param courseInfoModel
     * @param cId
     */
    private void saveCourseResource(CourseInfoModel courseInfoModel, int cId) {
        if (StringUtils.isNotBlank(courseInfoModel.getHeadImg())) {
            Resource titleBG = new Resource();
            titleBG.setParentId(cId);
            titleBG.setParentType("2");
            titleBG.setResType("1");
            titleBG.setResKey("camp_BG");
            titleBG.setTitle("檬营标题背景");
            titleBG.setUrl(courseInfoModel.getHeadImg());
            resourceMapper.insertSelective(titleBG);
        }

//        if (StringUtils.isNotBlank(courseInfoModel.getQunQRCodePic())) { 现在二维码统一直接由教练表读取 blank May 5 2017
//            Resource qunQRCodeResource = new Resource();
//            qunQRCodeResource.setParentId(cId);
//            qunQRCodeResource.setParentType("2");
//            qunQRCodeResource.setResType("1");
//            qunQRCodeResource.setResKey("QRCode");
//            qunQRCodeResource.setTitle("檬营QR群二维码");
//            qunQRCodeResource.setUrl(courseInfoModel.getQunQRCodePic());
//            resourceMapper.insertSelective(qunQRCodeResource);
//        }

        if (StringUtils.isNotBlank(courseInfoModel.getUrl())) {
            Resource videoResource = new Resource();
            videoResource.setParentId(cId);
            videoResource.setParentType("2");
            videoResource.setResType("2");
            videoResource.setUrl(courseInfoModel.getUrl());
            videoResource.setLink(courseInfoModel.getLink());
            videoResource.setResKey("camp_video");
            videoResource.setTitle("檬营视频预览");
            resourceMapper.insertSelective(videoResource);
        }

        String catePic = courseInfoModel.getCategoryPic();
        if (catePic.length() > 0) {
            String[] catePics = catePic.split(",");
            Resource catePicResource;
            for (String pic : catePics) {
                catePicResource = new Resource();
                catePicResource.setParentId(cId);
                catePicResource.setParentType("2");
                catePicResource.setResType("1");
                catePicResource.setUrl(pic);
                catePicResource.setResKey("camp_category");
                courseInfoModel.setTitle("檬营类别硬照");
                resourceMapper.insertSelective(catePicResource);
            }
        }
    }

    /**
     * 根据课程ID查询檬营课程
     * @param id
     * @return
     */
    @Override
    public CourseInfoModel queryCourseById(Integer id) {
        if (id == null )
            return  null;

        CourseInfoModel courseInfoModel = courseInfoMapper.queryCampCourseById(id);
        if (courseInfoModel.getResources() != null && courseInfoModel.getResources().size() > 0) {
            List<Resource> resources = courseInfoModel.getResources();

            StringBuilder sCatePic = new StringBuilder();
            for (Resource resource : resources) {

                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("camp_BG")) {
                    courseInfoModel.setHeadImg(resource.getUrl());
                }
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("camp_video")) {
                    courseInfoModel.setUrl(resource.getUrl());
                    courseInfoModel.setLink(resource.getLink());
                }
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("camp_category")) {
                    if (sCatePic.length() <= 0) {
                        sCatePic.append(resource.getUrl());
                    } else {
                        sCatePic.append("," + resource.getUrl());
                    }
                }
            }

            if (sCatePic.length() > 0) {
                courseInfoModel.setCategoryPic(sCatePic.toString());
            }
        }
        return courseInfoModel;
    }

    @Override
    public Map<String, Object> queryCourseTeamToList() {
        List<CoachInfo> coachInfoList = coachInfoMapper.selectList(null);

        List<StoreInfo> storeInfoList = storeInfoMapper.selectList(null);
//        CourseInfoExample courseInfoExample = new CourseInfoExample();
//        courseInfoExample.or().andIdIsNotNull().andCourseTypeEqualTo("2");
//        List<CourseInfo> courseInfoList = courseInfoMapper.selectByExample(courseInfoExample);
        Map<String, Object> map = new HashMap<>();
        map.put("coachList", coachInfoList);
        map.put("storeList", storeInfoList);

        CourseInfo courseInfo = new CourseInfo();
        courseInfo.setCourseType("2");
        EntityWrapper<CourseInfo> entityWrapper = new EntityWrapper<>(courseInfo);
        entityWrapper.isNotNull("id");
        map.put("courseList",courseInfoMapper.selectList(entityWrapper));
        return map;
    }

    @Override
    public CourseTeamInfo queryCourseTeamById(int id) {
        return courseInfoMapper.queryCourseTeamById(id);
    }
    /**
     * 获取课程相关资源
     */
	@Override
	public List<Resource> getResourceByCoursrId(Map<String, Object> map) {
		ResourceExample resourceE = new ResourceExample();
		String ids =  (String) map.get("courseId");
		int id = Integer.valueOf(ids);
		String key = (String)map.get("resKey");
		resourceE.or().andParentIdEqualTo(id).andParentTypeEqualTo("2").andResKeyEqualTo(key);
		List<Resource> list = resourceMapper.selectByExample(resourceE);
		return list;
	}

    /**
     * 檬营下架
     * @param id
     * @return
     */
    @Override
    public boolean closeCourseById(Integer id) {
        if (id <= 0) {
            return false;
        }
        CourseInfo courseInfo = new CourseInfo();
        courseInfo.setId(id);
        courseInfo.setStatus("3");

        return courseInfoMapper.updateSelectiveById(courseInfo) > 0;
    }
    
    /**
     * 课程修改
     */
	@Override
	public int updateCourseInfoToDel(Map<String, Object> map) {
		String courseIds = (String) map.get("courseId");
		String userId = (String) map.get("userId");
		CourseInfo courseInfo = courseInfoMapper.selectById(Integer.valueOf(courseIds));
		String status = courseInfo.getStatus();
		if("1".equals(status)){
			status = "4" ;
		}else if("2".equals(status)){
			status = "3";
		}else if("3".equals(status)){
			status = "4";
		}
		courseInfo.setStatus(status);
		courseInfo.setUpdatedBy(Integer.valueOf(userId));
		Date now = new Date();
		courseInfo.setUpdatedTime(now);
		int bool = courseInfoMapper.updateSelectiveById(courseInfo);
		return bool;
	}

	@Override
	public Map<String, Object> getCourseResources(Map<String, Object> map) {
		Map<String, Object> mapD = new HashMap<String, Object>();
		String standardIds = (String) map.get("standardId");
		int id = Integer.valueOf(standardIds);
		CourseStandard courseStandard = courseStandardMapper.selectById(id);
		ResourceExample example = new ResourceExample();
		example.or().andParentTypeEqualTo("4").andParentIdEqualTo(id);
		List<Resource> resourceList = resourceMapper.selectByExample(example);
		mapD.put("courseStandard", courseStandard);
		mapD.put("resourceList", resourceList);
		return mapD;
	}

    /**
     * 查询檬营订单
     * @param id
     * @return
     */
    @Override
    public int queryCourseOrderByCourseId(Integer id) {
        return courseInfoMapper.queryCourseOrderByCourseId(id);
    }
    
//    @Override
//    public List<CoachFeeDetailVo> queryCoachFeeDetail(Map<String, Object> param){
//    	return courseInfoMapper.queryCoachFeeDetail(param);
//    }
    
    @Override
    public List<CoachFeeDetailVo> queryCoachFeeDetail(Map<String, Object> paramsMap) {

    	return courseInfoMapper.queryCoachFeeDetail(paramsMap);
    }
 
}
